/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.table.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.ConstantVars;
import com.je.common.base.db.JEDatabase;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.db.PcDBMethodServiceFactory;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.*;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.table.DynaCache;
import com.je.meta.cache.table.TableCache;
import com.je.meta.model.view.ViewColumn;
import com.je.meta.model.view.ViewDdlVo;
import com.je.meta.model.view.ViewOuput;
import com.je.meta.rpc.develop.DevelopLogRpcService;
import com.je.meta.service.table.BuildAssociationDDLService;
import com.je.meta.service.table.MetaViewService;
import com.je.meta.service.table.template.DDlTemplateEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: jecloud-meta
 * @author: LIULJ
 * @create: 2021-09-18 11:25
 * @description: 视图服务实现
 */
@Service
public class MetaViewServiceImpl implements MetaViewService {

    @Autowired
    private MetaService metaService;
    @Lazy
    @Autowired
    private CommonService commonService;
    @Autowired
    private TableCache tableCache;
    @Autowired
    private DynaCache dynaCache;
    @Autowired
    private DevelopLogRpcService developLogRpcService;

    /**
     * 创建视图
     *
     * @param table 表
     * @return
     */
    @Override
    public DynaBean createView(DynaBean table) {
        String sql = table.getStr("RESOURCETABLE_SQL");
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        table.setStr("RESOURCETABLE_OLDTABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
        //创建视图
        //metaService.executeSql(" CREATE VIEW " + tableCode + " AS " + sql);
        metaService.executeSql(sql);
        return table;
    }

    /**
     * 持久视图信息
     *
     * @param table  持久化表数据
     * @param fields 持久化列
     * @return
     */
    @Override
    public DynaBean saveViewInfo(DynaBean table, String fields) {
        //获取视图列信息
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        DynaBean recourceTable = new DynaBean("JE_CORE_RESOURCETABLE", false);
        recourceTable.set("RESOURCETABLE_TABLECODE", tableCode);
        table.set("RESOURCETABLE_ISCREATE", "1");
        if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_ORACLE)
                || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SHENTONG)
                || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_KINGBASEES)
                || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_DM)) {
            recourceTable = DataBaseUtils.getViewBaseInfo(recourceTable, metaService.getConnection());
        } else if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SQLSERVER)) {
            recourceTable = DataBaseUtils.getViewBaseInfoBySQLServer(recourceTable, metaService.getConnection());
        } else if (JEDatabase.getCurrentDatabase().equals(ConstantVars.STR_MYSQL)) {
            recourceTable = DataBaseUtils.getViewBaseInfoByMySQL(recourceTable, metaService.getConnection());
        } else if (JEDatabase.getCurrentDatabase().equals(ConstantVars.STR_TIDB)) {
            recourceTable = DataBaseUtils.getViewBaseInfoByMySQL(recourceTable, metaService.getConnection());
        }
        List<DynaBean> columns = (List<DynaBean>) recourceTable.get(BeanService.KEY_TABLE_COLUMNS);
        //metaService.insert(table);
        String nowDate = DateUtils.formatDateTime(new Date());
        Map<String, net.sf.json.JSONObject> columnsInfo = buildColumnInfo(fields);
        String pkCode = "";
        for (DynaBean column : columns) {
            column.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLECOLUMN_ID");
            column.set("SY_CREATETIME", nowDate);
            column.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            column.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            column.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            column.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            column.set("TABLECOLUMN_OLDCODE", column.getStr("TABLECOLUMN_CODE"));
            column.set("TABLECOLUMN_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
            column.set("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
            column.set("TABLECOLUMN_UNIQUE", "0");
            column.set("TABLECOLUMN_CLASSIFY", "PRO");
            column.set("TABLECOLUMN_TREETYPE", "NORMAL");
            if (columnsInfo.get(column.getStr("TABLECOLUMN_CODE")) != null) {
                net.sf.json.JSONObject objs = columnsInfo.get(column.getStr("TABLECOLUMN_CODE"));
                column.set("TABLECOLUMN_NAME", objs.getString("name"));
                column.set("TABLECOLUMN_VIEWCONFIG", objs.toString());
                String type = objs.getString("dataType");//存储视图列的配置信息
                if (StringUtil.isNotEmpty(type)) {
                    column.set("TABLECOLUMN_TYPE", type);
                    if ("ID".equals(type)) {
                        pkCode = column.getStr("TABLECOLUMN_CODE");
                    }
                }

            }
            metaService.insert(column);
        }
        if (StringUtil.isNotEmpty(pkCode)) {
            DynaBean pk = new DynaBean("JE_CORE_TABLEKEY", false);
            pk.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLECOLUMN_ID");
            pk.set("TABLEKEY_CODE", "JE_" + DateUtils.getUniqueTime() + "_ID");
            pk.set("TABLEKEY_COLUMNCODE", pkCode);
            pk.set("TABLEKEY_TYPE", "Primary");
            pk.set("TABLEKEY_ISRESTRAINT", "1");
            pk.set("TABLEKEY_CHECKED", "1");
            pk.set("TABLEKEY_CLASSIFY", "SYS");
            pk.set("SY_ORDERINDEX", 0);
            pk.set("SY_CREATETIME", nowDate);
            pk.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            pk.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            pk.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            pk.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            pk.set("TABLEKEY_ISCREATE", "1");
            pk.set("TABLEKEY_TABLECODE", table.get("RESOURCETABLE_TABLECODE"));
            pk.set("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
            metaService.insert(pk);
            table.set("RESOURCETABLE_PKCODE", pkCode);
            metaService.update(table);
        }
        return table;
    }

    /**
     * 持久视图信息
     *
     * @param table     持久化表数据
     * @param viewOuput 输出视图数据
     * @return
     */
    @Override
    public DynaBean saveViewInfos(DynaBean table, List<ViewOuput> viewOuput, DynaBean dynaBean) {
        String masterTableId = table.getStr("masterTableId");
        table.table("JE_CORE_RESOURCETABLE");
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        DynaBean recourceTable = new DynaBean("JE_CORE_RESOURCETABLE", false);
        recourceTable.set("RESOURCETABLE_TABLECODE", tableCode);
        table.set("RESOURCETABLE_ISCREATE", "1");
        if (null == dynaBean) {
            if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_ORACLE)
                    || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SHENTONG)
                    || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_KINGBASEES)
                    || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_DM)) {
                recourceTable = DataBaseUtils.getViewBaseInfo(recourceTable, metaService.getConnection());
            } else if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SQLSERVER)) {
                recourceTable = DataBaseUtils.getViewBaseInfoBySQLServer(recourceTable, metaService.getConnection());
            } else if (JEDatabase.getCurrentDatabase().equals(ConstantVars.STR_MYSQL)) {
                recourceTable = DataBaseUtils.getViewBaseInfoByMySQL(recourceTable, metaService.getConnection());
            } else if (JEDatabase.getCurrentDatabase().equals(ConstantVars.STR_TIDB)) {
                recourceTable = DataBaseUtils.getViewBaseInfoByMySQL(recourceTable, metaService.getConnection());
            }
        } else {
            recourceTable = dynaBean;
        }
        List<DynaBean> columns = (List<DynaBean>) recourceTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
        //metaService.insert(table);
        String nowDate = DateUtils.formatDateTime(new Date());
        Map<String, ViewOuput> columnsInfo = ViewOuput.buildViewOuPutListToMap(viewOuput);
        String pkCode = "";
        for (DynaBean column : columns) {
            column.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLECOLUMN_ID");
            column.set("SY_CREATETIME", nowDate);
            column.table("JE_CORE_TABLECOLUMN");
            column.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            column.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            column.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            column.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            column.set("TABLECOLUMN_OLDCODE", column.getStr("TABLECOLUMN_CODE"));
            column.set("TABLECOLUMN_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
            column.set("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
            column.set("TABLECOLUMN_UNIQUE", "0");
            column.set("TABLECOLUMN_CLASSIFY", "PRO");
            column.set("TABLECOLUMN_TREETYPE", "NORMAL");
            ViewOuput buildViewOuput = columnsInfo.get(column.getStr("TABLECOLUMN_CODE"));
            column.set("TABLECOLUMN_NAME", buildViewOuput.getName());
            column.set("TABLECOLUMN_VIEWCONFIG", ViewOuput.toString(buildViewOuput, masterTableId));
            //存储视图列的配置信息
            String type = buildViewOuput.getDataType();
            column.set("TABLECOLUMN_TYPE", type);
            column.set("SY_ORDERINDEX", buildViewOuput.getOrderIndex());
            column.set("TABLECOLUMN_LENGTH", buildViewOuput.getLength());
            if ("ID".equals(type)) {
                pkCode = column.getStr("TABLECOLUMN_CODE");
            }
            metaService.insert(column);
        }
        if (StringUtil.isNotEmpty(pkCode)) {
            DynaBean pk = new DynaBean("JE_CORE_TABLEKEY", false);
            pk.set(BeanService.KEY_PK_CODE, "JE_CORE_TABLEKEY_ID");
            pk.set("TABLEKEY_CODE", "JE_" + DateUtils.getUniqueTime() + "_ID");
            pk.set("TABLEKEY_COLUMNCODE", pkCode);
            pk.set("TABLEKEY_TYPE", "Primary");
            pk.set("TABLEKEY_ISRESTRAINT", "1");
            pk.set("TABLEKEY_CHECKED", "1");
            pk.set("TABLEKEY_CLASSIFY", "SYS");
            pk.set("SY_ORDERINDEX", 0);
            pk.set("SY_CREATETIME", nowDate);
            pk.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            pk.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            pk.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            pk.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            pk.set("TABLEKEY_ISCREATE", "1");
            pk.set("TABLEKEY_TABLECODE", table.get("RESOURCETABLE_TABLECODE"));
            pk.set("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
            metaService.insert(pk);
            table.set("RESOURCETABLE_PKCODE", pkCode);
            metaService.update(table);
        }
        return table;
    }


    @Override
    public DynaBean updateViewCascadeInfo(DynaBean table, String cascade) {

        //如果没有级联关系则直接返回，不做处理
        if (Strings.isNullOrEmpty(cascade)) {
            return table;
        }

        //获取视图ID，获取不到应该抛出异常
        String mainId = table.getStr("JE_CORE_RESOURCETABLE_ID");
        if (Strings.isNullOrEmpty(mainId)) {
            throw new PlatformException(MessageUtils.getMessage("view.get.key"), PlatformExceptionEnum.UNKOWN_ERROR);
        }

        JSONArray cascadeJsonArray = JSONArray.parseArray(cascade);
        List<DynaBean> cascadeBeans = metaService.select("JE_CORE_VIEWCASCADE", ConditionsWrapper.builder().eq("JE_CORE_RESOURCETABLE_ID", mainId));

        List<String> reserveCascadeIds = Lists.newArrayList();
        JSONArray reversedJsonArray = new JSONArray();

        JSONObject eachCascadeObj;
        DynaBean eachCascadeBean;
        //获取保留的关联关系，此处的逻辑是保留相同的，所有不相同的删除，统一重新添加
        for (int i = 0; i < cascadeJsonArray.size(); i++) {
            eachCascadeObj = cascadeJsonArray.getJSONObject(i);
            for (int j = 0; cascadeBeans != null && j < cascadeBeans.size(); j++) {
                eachCascadeBean = cascadeBeans.get(j);
                if (eachCascadeBean.getStr("VIEWCASCADE_YBBM").equals(eachCascadeObj.getString("table1"))
                        && eachCascadeBean.getStr("VIEWCASCADE_MBBBM").equals(eachCascadeObj.getString("table2"))
                        && eachCascadeBean.getStr("VIEWCASCADE_YBZD").equals(eachCascadeObj.getString("code1"))
                        && eachCascadeBean.getStr("VIEWCASCADE_MBBZD").equals(eachCascadeObj.getString("code2"))
                        && eachCascadeBean.getStr("VIEWCASCADE_GLGX_CODE").equals(eachCascadeObj.getString("conn"))) {
                    reserveCascadeIds.add(eachCascadeBean.getStr("JE_CORE_RESOURCETABLE_ID"));
                    reversedJsonArray.add(eachCascadeBean);
                    break;
                }
            }
        }

        metaService.delete("JE_CORE_VIEWCASCADE", ConditionsWrapper.builder().eq("JE_CORE_RESOURCETABLE_ID", mainId).notIn("JE_CORE_VIEWCASCADE_ID", reserveCascadeIds));
        for (int i = 0; i < cascadeJsonArray.size(); i++) {
            eachCascadeObj = cascadeJsonArray.getJSONObject(i);
            boolean flag = false;
            for (int j = 0; j < reversedJsonArray.size(); j++) {
                if (eachCascadeObj.equals(reversedJsonArray.getJSONObject(j))) {
                    flag = true;
                    break;
                }
            }

            if (!flag) {
                DynaBean cascadeBean = new DynaBean("JE_CORE_VIEWCASCADE", false);
                cascadeBean.set("JE_CORE_RESOURCETABLE_ID", mainId);
                cascadeBean.set("VIEWCASCADE_YBBM", eachCascadeObj.getString("table1"));
                cascadeBean.set("VIEWCASCADE_YBZD", eachCascadeObj.getString("code1"));
                cascadeBean.set("VIEWCASCADE_MBBBM", eachCascadeObj.getString("table2"));
                cascadeBean.set("VIEWCASCADE_MBBZD", eachCascadeObj.getString("code2"));
                cascadeBean.set("VIEWCASCADE_GLGX_CODE", eachCascadeObj.getString("conn"));
                commonService.buildModelCreateInfo(cascadeBean);
                metaService.insert(cascadeBean);
            }

        }

        return table;
    }


    @Override
    public DynaBean updateViewCascadeInfos(DynaBean table, List<ViewColumn> viewColumn) {

        //如果没有级联关系则直接返回，不做处理
        if (viewColumn.size() < 0) {
            return table;
        }

        //获取视图ID，获取不到应该抛出异常
        String mainId = table.getStr("JE_CORE_RESOURCETABLE_ID");
        if (Strings.isNullOrEmpty(mainId)) {
            throw new PlatformException(MessageUtils.getMessage("view.get.key"), PlatformExceptionEnum.UNKOWN_ERROR);
        }

        List<DynaBean> cascadeBeans = metaService.select("JE_CORE_VIEWCASCADE", ConditionsWrapper.builder().eq("JE_CORE_RESOURCETABLE_ID", mainId));

        List<String> reserveCascadeIds = Lists.newArrayList();
        JSONArray reversedJsonArray = new JSONArray();

        DynaBean eachCascadeBean;
        //获取保留的关联关系，此处的逻辑是保留相同的，所有不相同的删除，统一重新添加
        for (int i = 0; i < viewColumn.size(); i++) {
            ViewColumn eachCascadeObj = viewColumn.get(i);
            for (int j = 0; cascadeBeans != null && j < cascadeBeans.size(); j++) {
                eachCascadeBean = cascadeBeans.get(j);
                if (eachCascadeBean.getStr("VIEWCASCADE_YBBM").equals(eachCascadeObj.getMainTableCode())
                        && eachCascadeBean.getStr("VIEWCASCADE_MBBBM").equals(eachCascadeObj.getTargetTableCode())
                        && eachCascadeBean.getStr("VIEWCASCADE_YBZD").equals(eachCascadeObj.getMainColumn())
                        && eachCascadeBean.getStr("VIEWCASCADE_MBBZD").equals(eachCascadeObj.getTargetColumn())
                        && eachCascadeBean.getStr("VIEWCASCADE_YBBS").equals(eachCascadeObj.getFormula())) {
                    reserveCascadeIds.add(eachCascadeBean.getStr("JE_CORE_RESOURCETABLE_ID"));
                    reversedJsonArray.add(eachCascadeBean);
                    break;
                }
            }
        }

        metaService.delete("JE_CORE_VIEWCASCADE", ConditionsWrapper.builder().eq("JE_CORE_RESOURCETABLE_ID", mainId).notIn("JE_CORE_VIEWCASCADE_ID", reserveCascadeIds));
        for (int i = 0; i < viewColumn.size(); i++) {
            ViewColumn eachCascadeObj = viewColumn.get(i);
            boolean flag = false;
            for (int j = 0; j < reversedJsonArray.size(); j++) {
                if (eachCascadeObj.equals(reversedJsonArray.getJSONObject(j))) {
                    flag = true;
                    break;
                }
            }

            if (!flag) {
                DynaBean cascadeBean = new DynaBean("JE_CORE_VIEWCASCADE", false);
                cascadeBean.set("JE_CORE_RESOURCETABLE_ID", mainId);
                cascadeBean.set("VIEWCASCADE_YBBM", eachCascadeObj.getMainTableCode());
                cascadeBean.set("VIEWCASCADE_YBZD", eachCascadeObj.getMainColumn());
                cascadeBean.set("VIEWCASCADE_MBBBM", eachCascadeObj.getTargetTableCode());
                cascadeBean.set("VIEWCASCADE_MBBZD", eachCascadeObj.getTargetColumn());
                cascadeBean.set("VIEWCASCADE_GLGX_CODE", eachCascadeObj.getFormula());
                cascadeBean.set("VIEWCASCADE_YBBS", eachCascadeObj.getMainIdentifier());
                cascadeBean.set("VIEWCASCADE_ZBBZ", eachCascadeObj.getTargetIdentifier());
                cascadeBean.set("VIEWCASCADE_YBID", eachCascadeObj.getMainTableId());
                cascadeBean.set("VIEWCASCADE_YBBMC", eachCascadeObj.getMainTableName());
                cascadeBean.set("VIEWCASCADE_ZBBMC", eachCascadeObj.getTargetTableName());
                cascadeBean.set("VIEWCASCADE_ZBID", eachCascadeObj.getTargetTableId());
                cascadeBean.set("VIEWCASCADE_SFXSX", eachCascadeObj.getIsDispalyLine());
                commonService.buildModelCreateInfo(cascadeBean);
                metaService.insert(cascadeBean);
            }

        }

        return table;
    }

    /**
     * 创建表和视图关系
     *
     * @param tableInfoList
     * @param resourcetableTablecode
     */
    @Override
    public void saveTableView(JSONArray tableInfoList, String resourcetableTablecode) {
        tableInfoList.forEach(tableCode -> {
            List<Map<String, Object>> maps = metaService.selectSql("SELECT * FROM JE_CORE_RESOURCETABLE WHERE RESOURCETABLE_TABLECODE={0}", tableCode);
            DynaBean cascadeBean = new DynaBean("JE_CORE_TABLEVIEW", false);
            cascadeBean.set("TABLEVIEW_RESOURCETABLE_ID", tableCode);
            cascadeBean.set("TABLEVIEW_VIEWCODE", resourcetableTablecode);
            cascadeBean.set("TABLEVIEW_VIEWNAME", maps.get(0).get("RESOURCETABLE_TABLENAME"));
            commonService.buildModelCreateInfo(cascadeBean);
            metaService.insert(cascadeBean);
        });
    }

    /**
     * 创建表和视图关系
     *
     * @param tableInfoList
     * @param resourcetableTablecode
     */
    @Override
    public void saveTableViews(List<String> tableInfoList, String resourcetableTablecode, boolean isUpdate) {
        if (isUpdate) {
            metaService.selectSql("DELETE FROM JE_CORE_TABLEVIEW WHERE TABLEVIEW_VIEWCODE={0}", resourcetableTablecode);
        }

        tableInfoList.forEach(tableCode -> {
            List<Map<String, Object>> maps = metaService.selectSql("SELECT * FROM JE_CORE_RESOURCETABLE WHERE RESOURCETABLE_TABLECODE={0}", tableCode);
            DynaBean cascadeBean = new DynaBean("JE_CORE_TABLEVIEW", false);
            cascadeBean.set("TABLEVIEW_RESOURCETABLE_ID", tableCode);
            cascadeBean.set("TABLEVIEW_VIEWCODE", resourcetableTablecode);
            cascadeBean.set("TABLEVIEW_VIEWNAME", maps.get(0).get("RESOURCETABLE_TABLENAME"));
            commonService.buildModelCreateInfo(cascadeBean);
            metaService.insert(cascadeBean);
        });
    }

    /**
     * 根据表编码获取表信息
     *
     * @param dynaBean
     * @return
     */
    @Override
    public DynaBean selectOneByCode(DynaBean dynaBean) {
        DynaBean table = metaService.selectOne("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE", dynaBean.get("RESOURCETABLE_TABLECODE")));
        return table;
    }

    /**
     * 修改视图
     *
     * @param table 修改视图数据信息
     * @return
     */
    @Override
    public DynaBean updateView(DynaBean table) {
        String sql = table.getStr("RESOURCETABLE_SQL");
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        table.setStr("RESOURCETABLE_OLDTABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
        String dbUpdateSql = PcDBMethodServiceFactory.getPcDBMethodService().getUpdateView();
        if (dbUpdateSql.contains("VIEW")) {
            dbUpdateSql = dbUpdateSql.replace("VIEW", "");
        }
        sql = sql.trim();
        String checkStr = sql.toUpperCase().substring(0, 10);
        if (checkStr.contains("CREATE")) {
            sql = sql.replaceFirst("CREATE", dbUpdateSql);
        }
        //metaService.executeSql(dbUpdateSql + " " + tableCode + " AS " + sql);
        metaService.executeSql(sql);
        return table;
    }


    /**
     * 持久视图信息
     *
     * @param table    视图信息
     * @param fields   需要的列信息
     * @param syncView 是否同步视图，是则不修改功能信息和键信息   只同步列信息
     * @return
     */
    @Override
    public DynaBean updateViewInfo(DynaBean table, String fields, Boolean syncView) {
        // TODO Auto-generated method stub
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        DynaBean recourceTable = new DynaBean("JE_CORE_RESOURCETABLE", false);
        recourceTable.set("RESOURCETABLE_TABLECODE", tableCode);
        table.set("RESOURCETABLE_ISCREATE", "1");
        if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_ORACLE)
                || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SHENTONG)
                || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_KINGBASEES)
                || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_DM)) {
            recourceTable = DataBaseUtils.getViewBaseInfo(recourceTable, metaService.getConnection());
        } else if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SQLSERVER)) {
            recourceTable = DataBaseUtils.getViewBaseInfoBySQLServer(recourceTable, metaService.getConnection());
        } else if (JEDatabase.getCurrentDatabase().equals(ConstantVars.STR_MYSQL)) {
            recourceTable = DataBaseUtils.getViewBaseInfoByMySQL(recourceTable, metaService.getConnection());
        } else if (JEDatabase.getCurrentDatabase().equals(ConstantVars.STR_TIDB)) {
            recourceTable = DataBaseUtils.getViewBaseInfoByMySQL(recourceTable, metaService.getConnection());
        }
        List<DynaBean> columns = (List<DynaBean>) recourceTable.get(BeanService.KEY_TABLE_COLUMNS);
        //需添加的列
        List<DynaBean> addColumns = new ArrayList<DynaBean>();
        //需修改的列
        List<DynaBean> updateColumns = new ArrayList<DynaBean>();
        //需删除的列
        List<String> delColumns = new ArrayList<String>();
        //构建  操作的列和键信息
        Set<String> haveCodes = new HashSet<String>();
        Map<String, net.sf.json.JSONObject> columnsInfo = buildColumnInfo(fields);
        List<DynaBean> oldColumns = metaService.select("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID")));
        String pkCode = table.getStr("RESOURCETABLE_PKCODE");
        for (DynaBean column : columns) {
            String columnCode = column.getStr("TABLECOLUMN_CODE");
            Boolean have = false;
            for (DynaBean oldColumn : oldColumns) {
                if (columnCode.equalsIgnoreCase(oldColumn.getStr("TABLECOLUMN_CODE"))) {
                    //如果找到相同的 修改
                    if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_NAME"))) {
                        oldColumn.set("TABLECOLUMN_NAME", column.getStr("TABLECOLUMN_NAME"));
                    }
                    oldColumn.set("TABLECOLUMN_CODE", column.getStr("TABLECOLUMN_CODE"));
                    oldColumn.set("TABLECOLUMN_TYPE", column.getStr("TABLECOLUMN_TYPE"));
                    oldColumn.set("TABLECOLUMN_LENGTH", column.getStr("TABLECOLUMN_LENGTH"));
                    oldColumn.set("TABLECOLUMN_ISNULL", column.getStr("TABLECOLUMN_ISNULL"));
                    String newPkCode = buildViewColumn(columnsInfo, oldColumn);
                    if (StringUtil.isEmpty(pkCode)) {
                        pkCode = newPkCode;
                    }
                    updateColumns.add(oldColumn);
                    have = true;
                    haveCodes.add(columnCode);
                    break;
                }
            }
            if (!have) {
                String newPkCode = buildViewColumn(columnsInfo, column);
                if (StringUtil.isEmpty(pkCode)) {
                    pkCode = newPkCode;
                }
                addColumns.add(column);
            }
        }
        if (StringUtil.isEmpty(pkCode) && StringUtil.isNotEmpty(table.getStr("RESOURCETABLE_PKCODE"))) {
            pkCode = table.getStr("RESOURCETABLE_PKCODE");
        }
        for (DynaBean oldColumn : oldColumns) {
            if (!haveCodes.contains(oldColumn.getStr("TABLECOLUMN_CODE"))) {
                delColumns.add(oldColumn.getStr("TABLECOLUMN_CODE"));
            }
        }
        String nowDate = DateUtils.formatDateTime(new Date());

        //处理列
        int index = updateColumns.size() + 1;
        for (DynaBean column : addColumns) {
            column.set("SY_CREATETIME", nowDate);
            column.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            column.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            column.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            column.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            column.set("TABLECOLUMN_OLDCODE", column.getStr("TABLECOLUMN_CODE"));
            column.set("TABLECOLUMN_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
            column.set("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
            column.set("TABLECOLUMN_UNIQUE", "0");
            column.set("TABLECOLUMN_ISCREATE", "1");
            column.set("TABLECOLUMN_CLASSIFY", "PRO");
            column.set("TABLECOLUMN_TREETYPE", "NORMAL");
            if (column.getStr("TABLECOLUMN_CODE", "").equals(pkCode)) {
                column.set("TABLECOLUMN_TYPE", "ID");
            }
            column.set("SY_ORDERINDEX", index);
            metaService.insert(column);
        }

        index = 0;
        for (DynaBean column : updateColumns) {
            column.set("TABLECOLUMN_ISCREATE", "1");
            column.set("SY_MODIFYTIME", nowDate);
            column.set("SY_MODIFYUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            column.set("SY_MODIFYUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            column.set("SY_MODIFYORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            column.set("SY_MODIFYORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            if (column.getStr("TABLECOLUMN_CODE", "").equals(pkCode)) {
                column.set("TABLECOLUMN_TYPE", "ID");
            }
            column.set("SY_ORDERINDEX", index++);
            metaService.update(column);
        }

        if (delColumns.size() > 0) {
            metaService.executeSql("DELETE FROM JE_CORE_TABLECOLUMN WHERE TABLECOLUMN_CODE IN ({0}) AND TABLECOLUMN_RESOURCETABLE_ID={1}", delColumns, table.getStr("JE_CORE_RESOURCETABLE_ID"));
        }

        //处理键
        if (StringUtil.isNotEmpty(pkCode)) {
            table.set("RESOURCETABLE_PKCODE", pkCode);
        }
        metaService.update(table);
        DynaBean tablePk = metaService.selectOne("JE_CORE_TABLEKEY", ConditionsWrapper.builder()
                .eq("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"))
                .eq("TABLEKEY_TYPE", "Primary")
        );
        Boolean updatePk = false;
        if (StringUtil.isNotEmpty(pkCode)) {
            if (tablePk != null && !pkCode.equals(tablePk.getStr("TABLEKEY_COLUMNCODE"))) {
                updatePk = true;
                tablePk.set("TABLEKEY_COLUMNCODE", pkCode);
                tablePk.set("TABLEKEY_CODE", pkCode + "_CODE");
                metaService.update(tablePk);
            }
        } else {
            if (tablePk != null && delColumns.contains(tablePk.getStr("TABLEKEY_COLUMNCODE"))) {
                metaService.delete("JE_CORE_TABLEKEY",
                        ConditionsWrapper.builder().eq("JE_CORE_TABLEKEY_ID", tablePk.getStr("JE_CORE_TABLEKEY_ID")));
            }
        }
        //处理功能
        List<DynaBean> funcs = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder().eq("FUNCINFO_TABLENAME", table.getStr("RESOURCETABLE_TABLECODE")));
        for (DynaBean fun : funcs) {
            String funId = fun.getStr("JE_CORE_FUNCINFO_ID");
            if (updatePk && StringUtils.isNotBlank(pkCode)) {
                fun.set("FUNCINFO_PKNAME", pkCode);
                metaService.update(fun);
            }
            if (delColumns.size() > 0) {
                metaService.executeSql("DELETE FROM JE_CORE_RESOURCECOLUMN WHERE RESOURCECOLUMN_CODE IN ({0}) AND RESOURCECOLUMN_FUNCINFO_ID={1}", delColumns, funId);
                metaService.executeSql("DELETE FROM JE_CORE_RESOURCEFIELD WHERE RESOURCEFIELD_CODE IN ({0}) AND RESOURCEFIELD_FUNCINFO_ID={1}", delColumns, funId);
            }
            if (addColumns.size() > 0 && !syncView) {
                String columnSql = "select RESOURCECOLUMN_CODE from JE_CORE_RESOURCECOLUMN where RESOURCECOLUMN_FUNCINFO_ID = {0} and RESOURCECOLUMN_IFIMPL = '1'";
                List<Map<String, Object>> mapList = metaService.selectSql(columnSql, funId);
                List<String> columnList = mapList.stream().map(p -> p.get("RESOURCECOLUMN_CODE").toString()).collect(Collectors.toList());


                mapList = metaService.selectSql("select max(SY_ORDERINDEX) AS ORDERINDEX  from JE_CORE_RESOURCECOLUMN where RESOURCECOLUMN_FUNCINFO_ID = {0} and RESOURCECOLUMN_IFIMPL = '1'", funId);
                List<Object> maxOrder = mapList.stream().map(p -> p.get("ORDERINDEX").toString()).collect(Collectors.toList());

                mapList = metaService.selectSql("select max(SY_ORDERINDEX) AS ORDERINDEX from JE_CORE_RESOURCEFIELD where RESOURCEFIELD_FUNCINFO_ID ={0} and RESOURCEFIELD_IFIMPL = '1'", funId);
                List<Object> fieldMaxOrder = mapList.stream().map(p -> p.get("ORDERINDEX").toString()).collect(Collectors.toList());


                Integer fieldOrderIndex = 0;
                Integer columnOrderIndex = 0;
                if (maxOrder != null && maxOrder.size() > 0) {
                    Object orderObj = maxOrder.iterator().next();
                    if (orderObj == null) {
                        orderObj = 0;
                    }
                    columnOrderIndex = Integer.parseInt(orderObj.toString());
                }
                if (fieldMaxOrder != null && fieldMaxOrder.size() > 0) {
                    Object orderObj = fieldMaxOrder.iterator().next();
                    if (orderObj == null) {
                        orderObj = 0;
                    }
                    fieldOrderIndex = Integer.parseInt(orderObj.toString());
                }
                for (Integer i = 0; i < addColumns.size(); i++) {
                    DynaBean column = addColumns.get(i);
                    if (!columnList.contains(column.getStr("TABLECOLUMN_CODE"))) {
                        DynaBean rc = new DynaBean("JE_CORE_RESOURCECOLUMN", false);
                        rc.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCECOLUMN_ID");
                        rc.set("RESOURCECOLUMN_FUNCINFO_ID", fun.getStr("JE_CORE_FUNCINFO_ID"));
                        rc.set("RESOURCECOLUMN_CODE", column.get("TABLECOLUMN_CODE"));
                        rc.set("RESOURCECOLUMN_NAME", column.get("TABLECOLUMN_NAME"));
                        //将导入的字段标识为true
                        rc.set("RESOURCECOLUMN_IFIMPL", "1");
                        //是否快速查询 false
                        rc.set("RESOURCECOLUMN_QUICKQUERY", "0");
                        rc.set("SY_ORDERINDEX", columnOrderIndex + i + 1);
                        //设置默认宽度为80
                        rc.set("RESOURCECOLUMN_WIDTH", "80");
                        //设置默认宽度为80
                        rc.set("RESOURCECOLUMN_WIDTH_EN", "80");
                        //是否拥有转换器conversion
                        rc.set("RESOURCECOLUMN_CONVERSION", "0");
                        //是否拥有转换器highlighting
                        rc.set("RESOURCECOLUMN_HIGHLIGHTING", "0");
                        //是否超链接hyperLink
                        rc.set("RESOURCECOLUMN_HYPERLINK", "0");
                        //是否在字典中取
                        rc.set("RESOURCECOLUMN_ISDD", "0");
                        //合并单元格      否
                        rc.set("RESOURCECOLUMN_MERGE", "0");
                        //锁定列  否
                        rc.set("RESOURCECOLUMN_LOCKED", "");
                        //多表头   否
                        rc.set("RESOURCECOLUMN_MORECOLUMN", "0");
                        rc.set("RESOURCECOLUMN_ISPK", "0");
                        //启用图标
                        rc.set("RESOURCECOLUMN_ENABLEICON", "0");
                        rc.set("RESOURCECOLUMN_SYSMODE", fun.getStr("FUNCINFO_SYSMODE"));
                        //是否可以为空  true
                        rc.set("RESOURCECOLUMN_ALLOWBLANK", "1");
                        //字段类型  默认为无  不可编辑
                        rc.set("RESOURCECOLUMN_QUERYTYPE", "no");
                        rc.set("RESOURCECOLUMN_XTYPE", "uxcolumn");
                        //列表编辑   默认为否
                        rc.set("RESOURCECOLUMN_ALLOWEDIT", "0");
                        rc.set("RESOURCECOLUMN_HIDDEN", "1");
                        rc.set("RESOURCECOLUMN_ALIGN", "left");
                        rc.set("RESOURCECOLUMN_INDEX", "0");
                        rc.set("RESOURCECOLUMN_ORDER", "0");
                        rc.set("SY_CREATETIME", nowDate);
                        rc.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
                        rc.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
                        rc.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
                        rc.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
                        metaService.insert(rc);
                        DynaBean rf = new DynaBean("JE_CORE_RESOURCEFIELD", false);
                        rf.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCEFIELD_ID");
                        rf.set("RESOURCEFIELD_FUNCINFO_ID", fun.getStr("JE_CORE_FUNCINFO_ID"));
                        rf.set("RESOURCEFIELD_CODE", column.get("TABLECOLUMN_CODE"));
                        rf.set("RESOURCEFIELD_NAME", column.get("TABLECOLUMN_NAME"));
                        //将导入的字段标识为true
                        rf.set("RESOURCEFIELD_IFIMPL", "1");
                        //是否可用  true
                        rf.set("RESOURCEFIELD_DISABLED", "1");
                        //默认序号为0
                        rf.set("SY_ORDERINDEX", fieldOrderIndex + i + 1);
                        //是否可以为空  true
                        rf.set("RESOURCEFIELD_ALLOWBLANK", "1");
                        //是否只读
                        rf.set("RESOURCEFIELD_READONLY", "0");
                        String columnType = column.getStr("TABLECOLUMN_TYPE");
                        //数值型
                        if ("NUMBER".equals(columnType) || "FLOAT".equals(columnType)) {
                            //字段类型   默认为文本框
                            rf.set("RESOURCEFIELD_XTYPE", "numberfield");
                            if ("FLOAT".equals(columnType) && StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_LENGTH"))) {
                                String lengthStr = column.getStr("TABLECOLUMN_LENGTH");
                                if (lengthStr.indexOf(",") != -1) {
                                    //默认小数精度
                                    rf.set("RESOURCEFIELD_CONFIGINFO", lengthStr.split(ArrayUtils.SPLIT)[1]);
                                } else {
                                    //默认小数精度
                                    rf.set("RESOURCEFIELD_CONFIGINFO", lengthStr);
                                }
                            } else if ("NUMBER".equals(columnType)) {
                                //默认小数精度
                                rf.set("RESOURCEFIELD_CONFIGINFO", "0");
                            }
                        } else if ("DATETIME".equals(columnType)) {
                            rf.set("RESOURCEFIELD_XTYPE", "datefield");
                            rf.setStr("RESOURCEFIELD_OTHERCONFIG", getDateOtherconfig("dateTime"));
                        } else if ("DATE".equals(columnType)) {
                            rf.set("RESOURCEFIELD_XTYPE", "datefield");
                            rf.setStr("RESOURCEFIELD_OTHERCONFIG", getDateOtherconfig("date"));
                        } else {
                            //字段类型   默认为文本框
                            rf.set("RESOURCEFIELD_XTYPE", "textfield");
                        }
                        //所占列数
                        rf.set("RESOURCEFIELD_COLSPAN", 1);
                        //可选可编辑   默认否
                        rf.set("RESOURCEFIELD_EDITABLE", "0");
                        rf.set("RESOURCEFIELD_HIDDEN", "1");
                        //所占行数
                        rf.set("RESOURCEFIELD_ROWSPAN", 1);
                        rf.set("RESOURCEFIELD_SYSMODE", fun.getStr("FUNCINFO_SYSMODE"));
                        rf.set("RESOURCEFIELD_ISPK", "0");
                        //根据列的添加方式 字典添加，表添加来快速初始化功能配置项
                        if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_DICCONFIG"))) {
                            String dicOtherConfig = column.getStr("TABLECOLUMN_DICQUERYFIELD");
                            if (StringUtil.isNotEmpty(dicOtherConfig)) {
                                if (dicOtherConfig.indexOf("cascadeField") != -1) {
                                    net.sf.json.JSONObject dicConfig = net.sf.json.JSONObject.fromObject(dicOtherConfig);
                                    String where = dicConfig.getString("where");
                                    String other = dicConfig.getString("other");
                                    rf.set("RESOURCEFIELD_XTYPE", "cbbfield");
                                    rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                                    rf.set("RESOURCEFIELD_OTHERCONFIG", other);
                                    rf.set("RESOURCEFIELD_WHERESQL", where);
                                } else {
                                    rf.set("RESOURCEFIELD_XTYPE", "treessfield");
                                    rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                                    rf.set("RESOURCEFIELD_OTHERCONFIG", URLDecoder.decode("%7B%22queryField%22%3A%22" + column.getStr("TABLECOLUMN_DICQUERYFIELD") + "%22%7D "));
                                }
                            } else {
                                rf.set("RESOURCEFIELD_XTYPE", "cbbfield");
                                rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                            }
                        } else if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_QUERYCONFIG"))) {
                            if (column.getStr("TABLECOLUMN_QUERYCONFIG").startsWith("JE_CORE_QUERYUSER,")) {
                                rf.set("RESOURCEFIELD_XTYPE", "vueuserfield");
                                rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_QUERYCONFIG"));
                                rf.set("RESOURCEFIELD_OTHERCONFIG", URLDecoder.decode("%7B%22DEPT%22%3A%221%22%2C%22ROLE%22%3A%221%22%2C%22SENTRY%22%3A%221%22%2C%22WORKGROUP%22%3A%221%22%7D"));
                            } else {
                                rf.set("RESOURCEFIELD_XTYPE", "gridssfield");
                                rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_QUERYCONFIG"));
                            }
                        }
                        rf.set("SY_CREATETIME", nowDate);
                        rf.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
                        rf.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
                        rf.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
                        rf.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
                        if ("1".equals(rf.getStr("RESOURCEFIELD_HIDDEN"))) {
                            rf.set("RESOURCEFIELD_FIELDLAZY", "0");
                        } else {
                            rf.set("RESOURCEFIELD_FIELDLAZY", "1");
                        }
                        metaService.insert(rf);
                    }
                }
            }
        }
        tableCache.clear(table.getStr("RESOURCETABLE_TABLECODE"));
        dynaCache.removeCache(table.getStr("RESOURCETABLE_TABLECODE"));
        clearMyBatisFuncCache(table.getStr("RESOURCETABLE_TABLECODE"));
        developLogRpcService.doDevelopLog("UPDATE_VIEW", "更新视图", "VIEW", "视图", table.getStr("RESOURCETABLE_TABLENAME"), table.getStr("RESOURCETABLE_TABLECODE"), table.getStr("JE_CORE_RESOURCETABLE_ID"), table.getStr("SY_PRODUCT_ID"));
        return table;
    }

    private String getDateOtherconfig(String type) {
        JSONObject jsonObject = new JSONObject();
        if ("date".equals(type)) {
            jsonObject.put("dateType", "date");
        } else {
            jsonObject.put("dateType", "dateTime");
        }
        return jsonObject.toString();
    }

    /**
     * 持久视图信息
     *
     * @param table         视图信息
     * @param viewOuputList 输出列信息
     * @param syncView      是否同步视图，是则不修改功能信息和键信息   只同步列信息
     * @return
     */
    @Override
    public DynaBean updateViewInfos(DynaBean table, List<ViewOuput> viewOuputList, boolean syncView, DynaBean dynaBean) {
        String masterTableId = table.getStr("masterTableId");
        table.table("JE_CORE_RESOURCETABLE");
        // TODO Auto-generated method stub
        String tableCode = table.getStr("RESOURCETABLE_TABLECODE");
        DynaBean recourceTable = new DynaBean("JE_CORE_RESOURCETABLE", false);
        recourceTable.set("RESOURCETABLE_TABLECODE", tableCode);
        table.set("RESOURCETABLE_ISCREATE", "1");
        if (null == dynaBean) {
            if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_ORACLE)
                    || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SHENTONG)
                    || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_KINGBASEES)
                    || JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_DM)) {
                recourceTable = DataBaseUtils.getViewBaseInfo(recourceTable, metaService.getConnection());
            } else if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SQLSERVER)) {
                recourceTable = DataBaseUtils.getViewBaseInfoBySQLServer(recourceTable, metaService.getConnection());
            } else if (JEDatabase.getCurrentDatabase().equals(ConstantVars.STR_MYSQL)) {
                recourceTable = DataBaseUtils.getViewBaseInfoByMySQL(recourceTable, metaService.getConnection());
            } else if (JEDatabase.getCurrentDatabase().equals(ConstantVars.STR_TIDB)) {
                recourceTable = DataBaseUtils.getViewBaseInfoByMySQL(recourceTable, metaService.getConnection());
            }
        } else {
            recourceTable = dynaBean;
        }
        List<DynaBean> columns = (List<DynaBean>) recourceTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
        //需添加的列
        List<DynaBean> addColumns = new ArrayList<DynaBean>();
        //需修改的列
        List<DynaBean> updateColumns = new ArrayList<DynaBean>();
        //需删除的列
        List<String> delColumns = new ArrayList<String>();
        //构建  操作的列和键信息
        Set<String> haveCodes = new HashSet<String>();
        Map<String, ViewOuput> columnsInfo = ViewOuput.buildViewOuPutListToMap(viewOuputList);
        List<DynaBean> oldColumns = metaService.select("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID")));
        String pkCode = table.getStr("RESOURCETABLE_PKCODE");
        for (DynaBean column : columns) {
            String columnCode = column.getStr("TABLECOLUMN_CODE");
            Boolean have = false;
            for (DynaBean oldColumn : oldColumns) {
                String TABLECOLUMN_TYPE = oldColumn.getStr("TABLECOLUMN_TYPE");
                if (columnCode.equalsIgnoreCase(oldColumn.getStr("TABLECOLUMN_CODE"))) {
                    //如果找到相同的 修改
                    if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_NAME"))) {
                        oldColumn.set("TABLECOLUMN_NAME", column.getStr("TABLECOLUMN_NAME"));
                    }
                    oldColumn.set("TABLECOLUMN_CODE", column.getStr("TABLECOLUMN_CODE"));
                    if (!"ID".equals(TABLECOLUMN_TYPE)) {
                        oldColumn.set("TABLECOLUMN_TYPE", column.getStr("TABLECOLUMN_TYPE"));
                    }
                    oldColumn.set("TABLECOLUMN_LENGTH", column.getStr("TABLECOLUMN_LENGTH"));
                    oldColumn.set("TABLECOLUMN_ISNULL", column.getStr("TABLECOLUMN_ISNULL"));
                    String newPkCode = buildViewColumnByNew(columnsInfo, oldColumn, masterTableId);
                    if (StringUtil.isEmpty(pkCode)) {
                        pkCode = newPkCode;
                    }
                    updateColumns.add(oldColumn);
                    have = true;
                    haveCodes.add(columnCode);
                    break;
                }
            }
            if (!have) {
                String newPkCode = buildViewColumnByNew(columnsInfo, column, masterTableId);
                if (StringUtil.isEmpty(pkCode)) {
                    pkCode = newPkCode;
                }
                addColumns.add(column);
            }
        }
        if (StringUtil.isEmpty(pkCode) && StringUtil.isNotEmpty(table.getStr("RESOURCETABLE_PKCODE"))) {
            pkCode = table.getStr("RESOURCETABLE_PKCODE");
        }
        for (DynaBean oldColumn : oldColumns) {
            if (!haveCodes.contains(oldColumn.getStr("TABLECOLUMN_CODE"))) {
                delColumns.add(oldColumn.getStr("TABLECOLUMN_CODE"));
            }
        }
        String nowDate = DateUtils.formatDateTime(new Date());

        //处理列
        int index = updateColumns.size() + 1;
        for (DynaBean column : addColumns) {
            ViewOuput viewOuput = columnsInfo.get(column.getStr("TABLECOLUMN_CODE"));
            column.table("JE_CORE_TABLECOLUMN");
            column.set("SY_CREATETIME", nowDate);
            column.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            column.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            column.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            column.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            column.set("TABLECOLUMN_OLDCODE", column.getStr("TABLECOLUMN_CODE"));
            column.set("TABLECOLUMN_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
            column.set("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
            column.set("TABLECOLUMN_UNIQUE", "0");
            column.set("TABLECOLUMN_ISCREATE", "1");
            column.set("TABLECOLUMN_CLASSIFY", "PRO");
            column.set("TABLECOLUMN_TREETYPE", "NORMAL");
            column.set("TABLECOLUMN_TYPE", viewOuput.getDataType());
            column.set("TABLECOLUMN_LENGTH", viewOuput.getLength());
            column.set("TABLECOLUMN_NAME", viewOuput.getName());
            if (column.getStr("TABLECOLUMN_CODE", "").equals(pkCode)) {
                column.set("TABLECOLUMN_TYPE", "ID");
            }
            column.set("SY_ORDERINDEX", index);
            metaService.insert(column);
        }

        index = 0;
        for (DynaBean column : updateColumns) {
            ViewOuput viewOuput = columnsInfo.get(column.getStr("TABLECOLUMN_CODE"));
            column.set("TABLECOLUMN_ISCREATE", "1");
            column.set("SY_MODIFYTIME", nowDate);
            column.set("SY_MODIFYUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
            column.set("SY_MODIFYUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
            column.set("SY_MODIFYORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
            column.set("SY_MODIFYORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
            column.set("TABLECOLUMN_TYPE", viewOuput.getDataType());
            column.set("TABLECOLUMN_LENGTH", viewOuput.getLength());
            column.set("TABLECOLUMN_NAME", viewOuput.getName());
            if (column.getStr("TABLECOLUMN_CODE", "").equals(pkCode)) {
                column.set("TABLECOLUMN_TYPE", "ID");
            }
            column.set("SY_ORDERINDEX", index++);
            metaService.update(column);
        }

        if (delColumns.size() > 0) {
            metaService.executeSql("DELETE FROM JE_CORE_TABLECOLUMN WHERE TABLECOLUMN_CODE IN ({0}) AND TABLECOLUMN_RESOURCETABLE_ID={1}", delColumns, table.getStr("JE_CORE_RESOURCETABLE_ID"));
        }

        //处理键
        if (StringUtil.isNotEmpty(pkCode)) {
            table.set("RESOURCETABLE_PKCODE", pkCode);
        }
        metaService.update(table);
        DynaBean tablePk = metaService.selectOne("JE_CORE_TABLEKEY", ConditionsWrapper.builder()
                .eq("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"))
                .eq("TABLEKEY_TYPE", "Primary")
        );
        Boolean updatePk = false;
        if (StringUtil.isNotEmpty(pkCode)) {
            if (tablePk != null && !pkCode.equals(tablePk.getStr("TABLEKEY_COLUMNCODE"))) {
                updatePk = true;
                tablePk.set("TABLEKEY_COLUMNCODE", pkCode);
                tablePk.set("TABLEKEY_CODE", pkCode + "_CODE");
                metaService.update(tablePk);
            }
        } else {
            if (tablePk != null && delColumns.contains(tablePk.getStr("TABLEKEY_COLUMNCODE"))) {
                metaService.delete("JE_CORE_TABLEKEY",
                        ConditionsWrapper.builder().eq("JE_CORE_TABLEKEY_ID", tablePk.getStr("JE_CORE_TABLEKEY_ID")));
            }
        }
        //处理功能
        List<DynaBean> funcs = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder().eq("FUNCINFO_TABLENAME", table.getStr("RESOURCETABLE_TABLECODE")));
        for (DynaBean fun : funcs) {
            String funId = fun.getStr("JE_CORE_FUNCINFO_ID");
            if (updatePk && StringUtils.isNotBlank(pkCode)) {
                fun.set("FUNCINFO_PKNAME", pkCode);
                metaService.update(fun);
            }
            if (delColumns.size() > 0) {
                metaService.executeSql("DELETE FROM JE_CORE_RESOURCECOLUMN WHERE RESOURCECOLUMN_CODE IN ({0}) AND RESOURCECOLUMN_FUNCINFO_ID={1}", delColumns, funId);
                metaService.executeSql("DELETE FROM JE_CORE_RESOURCEFIELD WHERE RESOURCEFIELD_CODE IN ({0}) AND RESOURCEFIELD_FUNCINFO_ID={1}", delColumns, funId);
            }
            if (addColumns.size() > 0 && !syncView) {
                String columnSql = "select RESOURCECOLUMN_CODE from JE_CORE_RESOURCECOLUMN where RESOURCECOLUMN_FUNCINFO_ID = {0} and RESOURCECOLUMN_IFIMPL = '1'";
                List<Map<String, Object>> mapList = metaService.selectSql(columnSql, funId);
                List<String> columnList = mapList.stream().map(p -> p.get("RESOURCECOLUMN_CODE").toString()).collect(Collectors.toList());


                mapList = metaService.selectSql("select max(SY_ORDERINDEX) AS ORDERINDEX  from JE_CORE_RESOURCECOLUMN where RESOURCECOLUMN_FUNCINFO_ID = {0} and RESOURCECOLUMN_IFIMPL = '1'", funId);
                List<Object> maxOrder = mapList.stream().map(p -> p.get("ORDERINDEX").toString()).collect(Collectors.toList());

                mapList = metaService.selectSql("select max(SY_ORDERINDEX) AS ORDERINDEX from JE_CORE_RESOURCEFIELD where RESOURCEFIELD_FUNCINFO_ID ={0} and RESOURCEFIELD_IFIMPL = '1'", funId);
                List<Object> fieldMaxOrder = mapList.stream().map(p -> p.get("ORDERINDEX").toString()).collect(Collectors.toList());


                Integer fieldOrderIndex = 0;
                Integer columnOrderIndex = 0;
                if (maxOrder != null && maxOrder.size() > 0) {
                    Object orderObj = maxOrder.iterator().next();
                    if (orderObj == null) {
                        orderObj = 0;
                    }
                    columnOrderIndex = Integer.parseInt(orderObj.toString());
                }
                if (fieldMaxOrder != null && fieldMaxOrder.size() > 0) {
                    Object orderObj = fieldMaxOrder.iterator().next();
                    if (orderObj == null) {
                        orderObj = 0;
                    }
                    fieldOrderIndex = Integer.parseInt(orderObj.toString());
                }
                for (Integer i = 0; i < addColumns.size(); i++) {
                    DynaBean column = addColumns.get(i);
                    if (!columnList.contains(column.getStr("TABLECOLUMN_CODE"))) {
                        DynaBean rc = new DynaBean("JE_CORE_RESOURCECOLUMN", false);
                        rc.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCECOLUMN_ID");
                        rc.set("RESOURCECOLUMN_FUNCINFO_ID", fun.getStr("JE_CORE_FUNCINFO_ID"));
                        rc.set("RESOURCECOLUMN_CODE", column.get("TABLECOLUMN_CODE"));
                        rc.set("RESOURCECOLUMN_NAME", column.get("TABLECOLUMN_NAME"));
                        //将导入的字段标识为true
                        rc.set("RESOURCECOLUMN_IFIMPL", "1");
                        //是否快速查询 false
                        rc.set("RESOURCECOLUMN_QUICKQUERY", "0");
                        rc.set("SY_ORDERINDEX", columnOrderIndex + i + 1);
                        //设置默认宽度为80
                        rc.set("RESOURCECOLUMN_WIDTH", "80");
                        //设置默认宽度为80
                        rc.set("RESOURCECOLUMN_WIDTH_EN", "80");
                        //是否拥有转换器conversion
                        rc.set("RESOURCECOLUMN_CONVERSION", "0");
                        //是否拥有转换器highlighting
                        rc.set("RESOURCECOLUMN_HIGHLIGHTING", "0");
                        //是否超链接hyperLink
                        rc.set("RESOURCECOLUMN_HYPERLINK", "0");
                        //是否在字典中取
                        rc.set("RESOURCECOLUMN_ISDD", "0");
                        //合并单元格      否
                        rc.set("RESOURCECOLUMN_MERGE", "0");
                        //锁定列  否
                        rc.set("RESOURCECOLUMN_LOCKED", "");
                        //多表头   否
                        rc.set("RESOURCECOLUMN_MORECOLUMN", "0");
                        rc.set("RESOURCECOLUMN_ISPK", "0");
                        //启用图标
                        rc.set("RESOURCECOLUMN_ENABLEICON", "0");
                        rc.set("RESOURCECOLUMN_SYSMODE", fun.getStr("FUNCINFO_SYSMODE"));
                        //是否可以为空  true
                        rc.set("RESOURCECOLUMN_ALLOWBLANK", "1");
                        //字段类型  默认为无  不可编辑
                        rc.set("RESOURCECOLUMN_QUERYTYPE", "no");
                        rc.set("RESOURCECOLUMN_XTYPE", "uxcolumn");
                        //列表编辑   默认为否
                        rc.set("RESOURCECOLUMN_ALLOWEDIT", "0");
                        rc.set("RESOURCECOLUMN_HIDDEN", "1");
                        rc.set("RESOURCECOLUMN_ALIGN", "left");
                        rc.set("RESOURCECOLUMN_INDEX", "0");
                        rc.set("RESOURCECOLUMN_ORDER", "0");
                        rc.set("SY_CREATETIME", nowDate);
                        rc.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
                        rc.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
                        rc.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
                        rc.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealUserName());
                        metaService.insert(rc);
                        DynaBean rf = new DynaBean("JE_CORE_RESOURCEFIELD", false);
                        rf.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCEFIELD_ID");
                        rf.set("RESOURCEFIELD_FUNCINFO_ID", fun.getStr("JE_CORE_FUNCINFO_ID"));
                        rf.set("RESOURCEFIELD_CODE", column.get("TABLECOLUMN_CODE"));
                        rf.set("RESOURCEFIELD_NAME", column.get("TABLECOLUMN_NAME"));
                        rf.set("RESOURCEFIELD_USE_SCOPE", "ALL");
                        //将导入的字段标识为true
                        rf.set("RESOURCEFIELD_IFIMPL", "1");
                        //是否可用  true
                        rf.set("RESOURCEFIELD_DISABLED", "1");
                        //默认序号为0
                        rf.set("SY_ORDERINDEX", fieldOrderIndex + i + 1);
                        //是否可以为空  true
                        rf.set("RESOURCEFIELD_ALLOWBLANK", "1");
                        //是否只读
                        rf.set("RESOURCEFIELD_READONLY", "0");
                        String columnType = column.getStr("TABLECOLUMN_TYPE");
                        //数值型
                        if ("NUMBER".equals(columnType) || "FLOAT".equals(columnType)) {
                            //字段类型   默认为文本框
                            rf.set("RESOURCEFIELD_XTYPE", "numberfield");
                            if ("FLOAT".equals(columnType) && StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_LENGTH"))) {
                                String lengthStr = column.getStr("TABLECOLUMN_LENGTH");
                                if (lengthStr.indexOf(",") != -1) {
                                    //默认小数精度
                                    rf.set("RESOURCEFIELD_CONFIGINFO", lengthStr.split(ArrayUtils.SPLIT)[1]);
                                } else {
                                    //默认小数精度
                                    rf.set("RESOURCEFIELD_CONFIGINFO", lengthStr);
                                }
                            } else if ("NUMBER".equals(columnType)) {
                                //默认小数精度
                                rf.set("RESOURCEFIELD_CONFIGINFO", "0");
                            }
                        } else if ("DATETIME".equals(columnType)) {
                            //字段类型
                            rf.set("RESOURCEFIELD_XTYPE", "datefield");
                            rf.setStr("RESOURCEFIELD_OTHERCONFIG", getDateOtherconfig("dateTime"));
                        } else if ("DATE".equals(columnType)) {
                            rf.set("RESOURCEFIELD_XTYPE", "datefield");
                            rf.setStr("RESOURCEFIELD_OTHERCONFIG", getDateOtherconfig("date"));
                        } else {
                            //字段类型   默认为文本框
                            rf.set("RESOURCEFIELD_XTYPE", "textfield");
                        }
                        //所占列数
                        rf.set("RESOURCEFIELD_COLSPAN", 1);
                        //可选可编辑   默认否
                        rf.set("RESOURCEFIELD_EDITABLE", "0");
                        rf.set("RESOURCEFIELD_HIDDEN", "1");
                        //所占行数
                        rf.set("RESOURCEFIELD_ROWSPAN", 1);
                        rf.set("RESOURCEFIELD_SYSMODE", fun.getStr("FUNCINFO_SYSMODE"));
                        rf.set("RESOURCEFIELD_ISPK", "0");
                        //根据列的添加方式 字典添加，表添加来快速初始化功能配置项
                        if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_DICCONFIG"))) {
                            String dicOtherConfig = column.getStr("TABLECOLUMN_DICQUERYFIELD");
                            if (StringUtil.isNotEmpty(dicOtherConfig)) {
                                if (dicOtherConfig.indexOf("cascadeField") != -1) {
                                    JSONObject dicConfig = JSONObject.parseObject(dicOtherConfig);
                                    String where = dicConfig.getString("where");
                                    String other = dicConfig.getString("other");
                                    rf.set("RESOURCEFIELD_XTYPE", "cbbfield");
                                    rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                                    rf.set("RESOURCEFIELD_OTHERCONFIG", other);
                                    rf.set("RESOURCEFIELD_WHERESQL", where);
                                } else {
                                    rf.set("RESOURCEFIELD_XTYPE", "treessfield");
                                    rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                                    rf.set("RESOURCEFIELD_OTHERCONFIG", URLDecoder.decode("%7B%22queryField%22%3A%22" + column.getStr("TABLECOLUMN_DICQUERYFIELD") + "%22%7D "));
                                }
                            } else {
                                rf.set("RESOURCEFIELD_XTYPE", "cbbfield");
                                rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_DICCONFIG"));
                            }
                        } else if (StringUtil.isNotEmpty(column.getStr("TABLECOLUMN_QUERYCONFIG"))) {
                            if (column.getStr("TABLECOLUMN_QUERYCONFIG").startsWith("JE_CORE_QUERYUSER,")) {
                                rf.set("RESOURCEFIELD_XTYPE", "vueuserfield");
                                rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_QUERYCONFIG"));
                                rf.set("RESOURCEFIELD_OTHERCONFIG", URLDecoder.decode("%7B%22DEPT%22%3A%221%22%2C%22ROLE%22%3A%221%22%2C%22SENTRY%22%3A%221%22%2C%22WORKGROUP%22%3A%221%22%7D"));
                            } else {
                                rf.set("RESOURCEFIELD_XTYPE", "gridssfield");
                                rf.set("RESOURCEFIELD_CONFIGINFO", column.getStr("TABLECOLUMN_QUERYCONFIG"));
                            }
                        }
                        rf.set("SY_CREATETIME", nowDate);
                        rf.set("SY_CREATEUSERID", SecurityUserHolder.getCurrentAccountRealUserId());
                        rf.set("SY_CREATEUSERNAME", SecurityUserHolder.getCurrentAccountRealUserName());
                        rf.set("SY_CREATEORGID", SecurityUserHolder.getCurrentAccountRealOrgId());
                        rf.set("SY_CREATEORGNAME", SecurityUserHolder.getCurrentAccountRealOrgName());
                        if ("1".equals(rf.getStr("RESOURCEFIELD_HIDDEN"))) {
                            rf.set("RESOURCEFIELD_FIELDLAZY", "0");
                        } else {
                            rf.set("RESOURCEFIELD_FIELDLAZY", "1");
                        }
                        metaService.insert(rf);
                    }
                }
            }
        }
        tableCache.clear(table.getStr("RESOURCETABLE_TABLECODE"));
        dynaCache.removeCache(table.getStr("RESOURCETABLE_TABLECODE"));
        return table;
    }

    /**
     * 创建视图数据和列索引等关系
     *
     * @param dynaBean
     * @param strData
     * @return
     */
    @Override
    @Transactional
    public DynaBean saveTableByView(DynaBean dynaBean, String strData) {
        buildViewTableId(dynaBean);
        ViewDdlVo viewDdlVo = ViewDdlVo.build(strData);
        List<ViewOuput> viewOuputList = viewDdlVo.getViewOuput();
        List<ViewColumn> viewColumnList = viewDdlVo.getViewColumn();
        String result = checkViewInfo(viewDdlVo, dynaBean);
        if (StringUtil.isNotEmpty(result)) {
            throw new PlatformException(result, PlatformExceptionEnum.UNKOWN_ERROR);
        }
        String masterTableId = viewDdlVo.getMasterTableId();

        //commonService.buildResourceTable(dynaBean);
        commonService.buildModelCreateInfo(dynaBean);
        String uuid = JEUUID.uuid();
        dynaBean.setStr(dynaBean.getPkCode(), uuid);
        dynaBean.set("SY_JECORE", "0");
        dynaBean.set("SY_JESYS", "1");
        dynaBean.set("RESOURCETABLE_TYPE", "VIEW");
        //保存表信息 je_core_resourcetable信息
        saveViewDdl(dynaBean);
        //执行DDL
        createView(dynaBean);
        dynaBean = metaService.selectOneByPk(dynaBean.getTableCode(), dynaBean.getPkValue());
        //保存视图关系列信息 JE_CORE_VIEWCASCADE
        dynaBean = updateViewCascadeInfos(dynaBean, viewColumnList);
        dynaBean.set("masterTableId", masterTableId);
        //保存表列信息 JE_CORE_TABLECOLUMN
        dynaBean = saveViewInfos(dynaBean, viewOuputList, null);
        //加载视图字段
        String masterTable = getTableCodeByTableIdOfViewDdVo(viewColumnList, viewOuputList, masterTableId);
        List<String> tableInfoList = getTableList(viewOuputList, masterTable);

        saveTableViews(tableInfoList, dynaBean.getTableCode(), false);
        clearMyBatisFuncCache(dynaBean.getStr("RESOURCETABLE_TABLECODE"));
        return dynaBean;
    }

    private boolean checkViewDDL(String createViewDDL) {
        String selectSql = getSelectSqlByCreateViewDDL(createViewDDL);
        try {
            metaService.selectSql(selectSql);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private String getSelectSqlByCreateViewDDL(String createViewDDL) {
        createViewDDL = createViewDDL.toUpperCase();
        int index = createViewDDL.indexOf(" AS ");
        return createViewDDL.substring(index + 3, createViewDDL.length());
    }

    private String checkRelevanceRepeat(List<ViewColumn> viewColumnList) {
        List<String> allStr = new ArrayList<>();
        for (ViewColumn viewColumn : viewColumnList) {
            allStr.add(viewColumn.getMainTableCode() + "_" + viewColumn.getMainColumn() + "." + viewColumn.getTargetTableCode() + "_" + viewColumn.getTargetColumn());
        }
        long distinctedSizeMain = allStr.stream().distinct().count();
        if (allStr.size() > distinctedSizeMain) {
            return MessageUtils.getMessage("table.view.relevance.field.repeat");
        }
        return null;
    }

    /**
     * 封装修改视图
     *
     * @param dynaBean
     * @param strData
     * @return
     */
    @Override
    @Transactional
    public DynaBean updateViews(DynaBean dynaBean, String strData) {
        ViewDdlVo viewDdlVo = JSONObject.parseObject(strData, ViewDdlVo.class);
        buildViewTableId(dynaBean);
        List<ViewOuput> viewOuputList = viewDdlVo.getViewOuput();
        List<ViewColumn> viewColumnList = viewDdlVo.getViewColumn();

        String result = checkViewInfo(viewDdlVo, dynaBean);
        if (StringUtil.isNotEmpty(result)) {
            throw new PlatformException(result, PlatformExceptionEnum.UNKOWN_ERROR);
        }
        String masterTableId = viewDdlVo.getMasterTableId();
        commonService.buildModelModifyInfo(dynaBean);
        DynaBean table = updateView(dynaBean);
        table.set("masterTableId", masterTableId);
        table = updateViewInfos(table, viewOuputList, false, null);
        table = updateViewCascadeInfos(table, viewColumnList);
        //加载视图字段
        String masterTable = getTableCodeByTableIdOfViewDdVo(viewColumnList, viewOuputList, masterTableId);
        List<String> tableInfoList = getTableList(viewOuputList, masterTable);
        saveTableViews(tableInfoList, dynaBean.getTableCode(), true);
        clearMyBatisFuncCache(dynaBean.getStr("RESOURCETABLE_TABLECODE"));
        developLogRpcService.doDevelopLog("UPDATE_VIEW", "更新视图", "VIEW", "视图", dynaBean.getStr("RESOURCETABLE_TABLENAME"), dynaBean.getStr("RESOURCETABLE_TABLECODE"), dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"), dynaBean.getStr("SY_PRODUCT_ID"));
        return table;
    }

    private String checkViewInfo(ViewDdlVo viewDdlVo, DynaBean dynaBean) {
        String result = "";
        result = checkViewInfoOnLocal(viewDdlVo, dynaBean);
        if (StringUtil.isEmpty(result)) {
            result = checkViewInfoOnMeta(viewDdlVo, dynaBean);
        }
        return result;

    }

    private String checkViewInfoOnMeta(ViewDdlVo viewDdlVo, DynaBean dynaBean) {
        String result = "";
        List<ViewColumn> viewColumnList = viewDdlVo.getViewColumn();
        //检查关联关系是否重复
        result = checkRelevanceRepeat(viewColumnList);
        if (StringUtil.isEmpty(result)) {
            List<ViewOuput> viewOuputList = viewDdlVo.getViewOuput();
            //检查输出列是否重复
            String repeat = ViewDdlVo.checkRepeatField(viewOuputList);
            if (StringUtil.isNotEmpty(repeat)) {
                result = MessageUtils.getMessage("table.view.output.field.repeat", repeat);
            }
        }
        return result;

    }

    private String checkViewInfoOnLocal(ViewDdlVo viewDdlVo, DynaBean dynaBean) {
        //检查SQL是否正确
        if (!checkViewDDL(dynaBean.getStr("RESOURCETABLE_SQL"))) {
            return MessageUtils.getMessage("table.view.ddl.wrong");
        }
        return null;
    }

    public void clearMyBatisFuncCache(String tableCode) {
        List<DynaBean> funcinfoList = metaService.select("JE_CORE_FUNCINFO", ConditionsWrapper.builder().eq("FUNCINFO_TABLENAME", tableCode));
        for (DynaBean funcinfo : funcinfoList) {
            metaService.clearMyBatisFuncCache(funcinfo.getStr("FUNCINFO_FUNCCODE"));
        }
    }

    /**
     * 解析视图位置信息，将视图所用的表，存储起来，删除表的时候添加判断是否可以删除
     */
    private void buildViewTableId(DynaBean dynaBean) {
        String coordinate = dynaBean.getStr("RESOURCETABLE_COORDINATE");
        if (!Strings.isNullOrEmpty(coordinate)) {
            try {
                StringBuffer tableCodeSb = new StringBuffer();
                JSONArray tables = JSONArray.parseArray(coordinate);
                for (Object table : tables) {
                    JSONObject tablejo = (JSONObject) table;
                    tableCodeSb.append(tablejo.getString("tableId") + ",");
                }
                dynaBean.setStr("RESOURCETABLE_TABLESINFO", tableCodeSb.toString());
            } catch (Exception e) {
                throw new PlatformException("视图位置信息解析失败", PlatformExceptionEnum.JE_CORE_TABLE_ERROR);
            }
        }
    }


    /**
     * 根据指定主键获取主表名称在VIEWVO返回封装类中，单表也可以创建视图
     *
     * @param viewColumnList
     * @param masterTableId
     * @return
     */
    @Override
    public String getTableCodeByTableIdOfViewDdVo(List<ViewColumn> viewColumnList, List<ViewOuput> viewOupuList, String masterTableId) {
        String masterTable = null;
        //单表逻辑
        if (viewColumnList.size() == 0) {
            for (ViewOuput viewOuput : viewOupuList) {
                if (viewOuput.getColumn().equals(masterTableId)) {
                    masterTable = viewOuput.getTableCode();
                }
            }
        }
        //多表逻辑
        for (int i = 0; i < viewOupuList.size(); i++) {
            ViewOuput viewOuput = viewOupuList.get(i);
            if (viewOuput.getColumn().equals(masterTableId)) {
                masterTable = viewOuput.getTableCode();
                return masterTable;
            }
        }
        return masterTable;
    }

    /**
     * 创建资源表中视图表数据
     *
     * @param table
     * @return
     */
    @Override
    public int saveViewDdl(DynaBean table) {
        DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", table.getStr("SY_PARENT"));
        table.table("JE_CORE_RESOURCETABLE");
        table.setStr("RESOURCETABLE_ICON", "jeicon jeicon-process");
        table.set("RESOURCETABLE_ISCREATE", 1);
        table.setStr("RESOURCETABLE_TYPE", "VIEW");
        table.set("RESOURCETABLE_ISUSEFOREIGNKEY", 0);
        table.set("RESOURCETABLE_MOREROOT", 0);
        table.set("SY_LAYER", dynaBean.getInt("SY_LAYER") + 1);
        table.setStr("SY_NODETYPE", "LEAF");
        table.set("SY_DISABLED", 0);
        dynaBean.set("SY_JECORE", "0");
        dynaBean.set("SY_JESYS", "1");
        String syProductId = dynaBean.getStr("SY_PRODUCT_ID");
        DynaBean productTable = new DynaBean();
        String syProductCode;
        productTable = metaService.selectOneByPk("JE_PRODUCT_MANAGE", syProductId);
        syProductCode = productTable.getStr("SY_PRODUCT_CODE");
        table.set("SY_PRODUCT_ID", syProductId);
        table.set("SY_PRODUCT_NAME", productTable.getStr("PRODUCT_NAME"));
        if (StringUtil.isEmpty(syProductCode)) {
            table.set("SY_PRODUCT_CODE", "");
        } else {
            table.set("SY_PRODUCT_CODE", syProductCode);
        }
        table.set("SY_PRODUCT_CODE", productTable.getStr("PRODUCT_CODE"));
        if (StringUtil.isNotEmpty(dynaBean.getStr("SY_PATH"))) {
            table.set("SY_PATH", dynaBean.getStr("SY_PATH") + "/" + table.getPkValue());
        }
        table.setStr("SY_PARENTPATH", dynaBean.getStr("SY_PATH"));
        commonService.buildModelCreateInfo(table);
        commonService.generateTreeOrderIndex(table);
        return metaService.insert(table);
    }

    /**
     * 获取视图ddl
     *
     * @param columnListList
     * @param ouputListList
     * @param viewCode
     * @param masterTableId
     * @return
     */
    @Override
    public StringBuilder generateViewDdl(List<ViewColumn> columnListList, List<ViewOuput> ouputListList, String viewCode, String masterTableId) {
        String result = checkRelevanceRepeat(columnListList);
        if (!StringUtil.isEmpty(result)) {
            throw new PlatformException(MessageUtils.getMessage("table.view.relevance.field.repeat"), PlatformExceptionEnum.JE_CORE_TABLE_CHECKCOLUMN_ERROR);
        }
        String masterTable = getTableCodeByTableIdOfViewDdVo(columnListList, ouputListList, masterTableId);
        StringBuilder groupDdl = new StringBuilder("");
        StringBuilder orderDdl = new StringBuilder("");
        StringBuilder whereDdl = new StringBuilder("");
        // Map<String, StringBuilder> joinMap = new HashMap<String, StringBuilder>(16);
        List<String> tableList = new ArrayList<String>(ouputListList.size());
        boolean isJoin = false;

        tableList = getTableList(ouputListList, masterTable);
        StringBuilder columnDdl = getColumnDdl(ouputListList, masterTable);
        groupDdl = getGroupDdl(ouputListList);
        orderDdl = getOrderDdl(ouputListList);
        String associationDdl = "";
        if (columnListList != null && columnListList.size() > 0) {
            associationDdl = getAssociationDdl(columnListList);
        } else {
            associationDdl = " FROM "+ouputListList.get(0).getTableCode();
        }
        //joinMap = getJoinDdl(columnListList, masterTable);
        whereDdl = getWhereDdl(ouputListList);
       /* if (joinMap.get("isJoin").toString().equals("1")) {
            isJoin = true;
        }
        joinMap.remove("isJoin");*/
        StringBuilder ddl = buildCreateViewDDL(isJoin, viewCode, columnDdl, associationDdl, whereDdl, groupDdl, orderDdl, tableList);
        return ddl;
    }

    private String getAssociationDdl(List<ViewColumn> associationList) {
        DDlTemplateEnum dDlTemplateEnum = selectTemplate(associationList);
        String template = dDlTemplateEnum.getTemplate();
        String beanName = dDlTemplateEnum.getBeanName();
        BuildAssociationDDLService buildAssociationDDLService = SpringContextHolder.getBean(beanName);
        return buildAssociationDDLService.createDdl(template, associationList);
    }

    private DDlTemplateEnum selectTemplate(List<ViewColumn> associationList) {
        if (associationList == null || associationList.size() == 0) {
            return DDlTemplateEnum.CONVENTION;
        }
        List<String> join = Lists.newArrayList(
                "LEFT JOIN", "RIGHT JOIN"
        );
       /* List<String> dika = Lists.newArrayList(
                "JOIN"
        );*/
        List<String> convention = Lists.newArrayList(
                "=", ">", "<", "!=", ">=", "<=", "JOIN"
        );

        List<String> formulas = new ArrayList<>();
        if (associationList.size() == 1) {
            String formula = associationList.get(0).getFormula();
            if (StringUtil.isEmpty(formula)) {
                return DDlTemplateEnum.CONVENTION;
            }
            if ("LEFT JOIN".equals(formula) || "RIGHT JOIN".equals(formula)) {
                return DDlTemplateEnum.ONE_JOIN;
            } else if ("JOIN".equals(formula)) {
                //笛卡尔积
                return DDlTemplateEnum.CONVENTION;
            } else {
                return DDlTemplateEnum.CONVENTION;
            }
        } else {
            for (ViewColumn viewColumn : associationList) {
                if (StringUtil.isNotEmpty(viewColumn.getFormula())) {
                    formulas.add(viewColumn.getFormula());
                }
            }
        }

        if (CollectionUtils.containsAny(join, formulas) && CollectionUtils.containsAny(convention, formulas)) {
            return DDlTemplateEnum.CONVENTION_AND_JOIN;
        } else if (CollectionUtils.containsAny(join, formulas)) {
            return DDlTemplateEnum.MORE_JOIN;
        } else if (CollectionUtils.containsAny(convention, formulas)) {
            return DDlTemplateEnum.CONVENTION;
        }
        return null;
    }

    private StringBuilder getWhereDdl(List<ViewOuput> ouputListList) {
        StringBuilder ddl = new StringBuilder();
        for (int i = 0, size = ouputListList.size(); i < size; i++) {
            ViewOuput column = ouputListList.get(i);
            String whereColumn = column.getWhereColum();
            String value = column.getValue();
            if (StringUtil.isEmpty(whereColumn) || StringUtil.isEmpty(value)) {
                continue;
            }
            ddl.append(" AND ").append(value).append(" ").append(whereColumn);
        }
        return ddl;
    }

    private StringBuilder buildCreateViewDDL(boolean isJoin, String viewCode, StringBuilder columnDdl, String association, StringBuilder whereDdl, StringBuilder groupDdl, StringBuilder orderDdl, List<String> tableList) {
        StringBuilder ddl = new StringBuilder("");
        ddl.append("CREATE VIEW " + viewCode + " AS ");
        ddl.append(columnDdl);
        ddl.append("\n");
        ddl.append(association);
        ddl.append(whereDdl);
        ddl.append(groupDdl);
        ddl.append(orderDdl);
        /*if (isJoin) {
            StringBuilder joinDdl = new StringBuilder("");
            StringBuilder andDdl = new StringBuilder("");
            for (String key : joinMap.keySet()) {
                if (key.contains("and")) {
                    andDdl.append(joinMap.get(key));
                } else {
                    joinDdl.append(joinMap.get(key));
                }
            }
            ddl.append(joinDdl);
            ddl.append(andDdl);

        } else {
            for (String childrenTable : tableList) {
                ddl.append("," + childrenTable);
            }
            if (joinMap.size() > 0) {
                for (String key : joinMap.keySet()) {
                    ddl.append(joinMap.get(key));
                }
            } else {
                ddl.append(" WHERE 1=1");
            }
            ddl.append(whereDdl);
            ddl.append(groupDdl);
            ddl.append(orderDdl);
        }*/
        return ddl;
    }

    private String buildWhereSql(String ddl) {
        ddl = ddl.trim();
        if (ddl.startsWith("AND")) {
            ddl = ddl.replaceFirst("AND", " WHERE ");
        }

        return ddl;
    }


    /**
     * 获取所有子表
     *
     * @param ouputListList
     * @param masterTable
     * @return
     */
    @Override
    public List<String> getTableList(List<ViewOuput> ouputListList, String masterTable) {
        List<String> tableList = new ArrayList<String>(ouputListList.size());
        for (int i = 0, size = ouputListList.size(); i < size; i++) {
            ViewOuput viewOuput = ouputListList.get(i);
            String tableCode = viewOuput.getTableCode();
            if (!(tableCode.equals(masterTable))) {
                if (tableList.contains(tableCode) || StringUtil.isEmpty(tableCode)) {
                    continue;
                }
                tableList.add(tableCode);
            }

        }
        return tableList;
    }

    /**
     * 获取关联条件ddl
     *
     * @param columnListList
     * @param masterTable
     * @return
     */
    @Override
    public Map<String, StringBuilder> getJoinDdl(List<ViewColumn> columnListList, String masterTable) {
        Map<String, StringBuilder> joinMap = new HashMap<String, StringBuilder>(16);
        boolean isJoin = false;
        for (int i = 0, size = columnListList.size(); i < size; i++) {
            StringBuilder joinDdl = new StringBuilder("");
            ViewColumn viewColumn = columnListList.get(i);

            String mainTableCode = viewColumn.getMainTableCode();//2
            String targetTableCode = viewColumn.getTargetTableCode();//1
            String MainColumn = viewColumn.getMainColumn();
            String targetColumn = viewColumn.getTargetColumn();
            String formula = viewColumn.getFormula();

            boolean isMaster = masterTable.equals(mainTableCode);
            List<String> joinList = new ArrayList<String>();
            joinList.add("LEFT JOIN");
            joinList.add("RIGHT JOIN");
            joinList.add("JOIN");

            if (joinList.contains(formula)) {
                if (isMaster) {
                    joinDdl.append(" " + formula + " " + targetTableCode + " ON " + masterTable + "." + MainColumn + " = " + targetTableCode + "." + targetColumn);
                } else {
                    joinDdl.append(" " + formula + " " + mainTableCode + " ON " + masterTable + "." + targetColumn + " = " + mainTableCode + "." + MainColumn);
                }
                joinMap.put("joinddl" + i, joinDdl);
                isJoin = true;
            } else {
                String mainTable = "";
                String targetTable = "";
                if (StringUtil.isNotEmpty(mainTableCode)) {
                    mainTable = mainTableCode + ".";
                }
                if (StringUtil.isNotEmpty(targetTableCode)) {
                    targetTable = targetTableCode + ".";
                }
                if (i == 0) {
                    joinDdl.append(" WHERE ");
                    joinDdl.append(mainTable + MainColumn + formula + targetTable + targetColumn);
                } else {
                    joinDdl.append(" AND " + mainTable + MainColumn + formula + targetTable + targetColumn);
                }
                joinMap.put("and" + i, joinDdl);
            }

        }
        if (isJoin) {
            joinMap.put("isJoin", new StringBuilder("1"));
        } else {
            joinMap.put("isJoin", new StringBuilder("0"));
        }
        return joinMap;
    }

    /**
     * 获取排序ddl语句
     *
     * @param ouputListList
     * @return
     */
    @Override
    public StringBuilder getOrderDdl(List<ViewOuput> ouputListList) {
        StringBuilder ddl = new StringBuilder();
        boolean flag = false;
        for (int i = 0, size = ouputListList.size(); i < size; i++) {
            ViewOuput column = ouputListList.get(i);
            String whereColumn = column.getColumn();
            String tableCode = column.getTableCode();
            String sort = column.getSort();
            String value = column.getValue();
            if (!(StringUtil.isEmpty(sort))) {
                if (!flag) {
                    ddl.append(" ORDER BY ");
                    flag = true;
                }
                ddl.append(value + " " + sort);
                if (flag) {
                    ddl.append(" ,");
                }
            }
        }
        String sortDdl = ddl.toString();
        if (!StringUtil.isEmpty(sortDdl)) {
            sortDdl = sortDdl.substring(0, sortDdl.length() - 1);
        }
        return new StringBuilder(sortDdl);
    }

    /**
     * 获取分组ddl拼接语句
     *
     * @param ouputListList
     * @return
     */
    @Override
    public StringBuilder getGroupDdl(List<ViewOuput> ouputListList) {
        StringBuilder ddl = new StringBuilder();
        boolean flag = false;
        for (int i = 0, size = ouputListList.size(); i < size; i++) {
            ViewOuput column = ouputListList.get(i);
            String whereColumn = column.getColumn();
            boolean hasGroup = column.isGrouping();
            String tableCode = column.getTableCode();
            String value = column.getValue();
            if (hasGroup) {
                if (!flag) {
                    ddl.append(" GROUP BY ");
                    flag = true;
                }
                ddl.append(value);
                if (flag) {
                    ddl.append(" ,");
                }

            }
        }
        String viewDdl = ddl.toString();
        if (!StringUtil.isEmpty(viewDdl)) {
            viewDdl = viewDdl.substring(0, viewDdl.length() - 1);
        }
        return new StringBuilder(viewDdl);
    }

    /**
     * 获取普通列组合DDL
     *
     * @param ouputListList
     * @param masterTable
     * @return
     */
    @Override
    public StringBuilder getColumnDdl(List<ViewOuput> ouputListList, String masterTable) {
        StringBuilder ddl = new StringBuilder();
        ddl.append("SELECT ");
        for (int i = 0, size = ouputListList.size(); i < size; i++) {
            ViewOuput column = ouputListList.get(i);
            String formula = column.getFormula();
            String tableCode = column.getTableCode();
            String columnCode = column.getColumn();
            String value = column.getValue();
            String asSql = "";
            //公式
            if (!(StringUtil.isEmpty(formula))) {
                String chSql = formula + String.format("(%s %s)", value, asSql) + " AS " + columnCode;
                ddl.append(chSql);
            } else {
                String chSql = value + " AS " + columnCode;
                ddl.append(chSql);
            }

            if (size - 1 != i) {
                ddl.append(", ");
            }
        }
        //ddl.append(" FROM " + masterTable);
        return ddl;
    }

    /**
     * 将数组的视图列信息 构建成map code为键 信息为值
     *
     * @param fields
     * @return
     */
    private Map<String, net.sf.json.JSONObject> buildColumnInfo(String fields) {
        Map<String, net.sf.json.JSONObject> columnInfos = new HashMap<String, net.sf.json.JSONObject>();
        net.sf.json.JSONArray columns = net.sf.json.JSONArray.fromObject(fields);
        for (Integer i = 0; i < columns.size(); i++) {
            net.sf.json.JSONObject objs = columns.getJSONObject(i);
            net.sf.json.JSONObject values = new net.sf.json.JSONObject();
            values.put("name", objs.get("name"));
            values.put("code", objs.get("code"));
            values.put("value", objs.get("value"));
            values.put("dataType", objs.get("dataType"));
            values.put("table", objs.get("table"));
            values.put("length", objs.get("length"));
            values.put("formula", objs.get("formula"));
            values.put("group", objs.get("group"));
            values.put("order", objs.get("order"));
            values.put("whereValue", objs.get("whereValue"));
            columnInfos.put(objs.getString("code").toUpperCase(), values);
        }
        return columnInfos;
    }


    private String buildViewColumn(Map<String, net.sf.json.JSONObject> columnsInfo, DynaBean column) {
        String pkCode = "";
        if (columnsInfo.get(column.getStr("TABLECOLUMN_CODE")) != null) {
            net.sf.json.JSONObject objs = columnsInfo.get(column.getStr("TABLECOLUMN_CODE"));
            column.set("TABLECOLUMN_NAME", objs.getString("name"));
            column.set("TABLECOLUMN_VIEWCONFIG", objs.toString());
            //存储视图列的配置信息
            String type = objs.getString("dataType");
            if (StringUtil.isNotEmpty(type)) {
                column.set("TABLECOLUMN_TYPE", type);
                if (objs.containsKey("length")) {
                    column.set("TABLECOLUMN_LENGTH", objs.getString("length"));
                }
                if ("ID".equals(type)) {
                    pkCode = column.getStr("TABLECOLUMN_CODE");
                }
            }

        }
        return pkCode;
    }

    private String buildViewColumnByNew(Map<String, ViewOuput> columnsInfo, DynaBean column, String masterTableId) {
        String pkCode = "";
        if (columnsInfo.get(column.getStr("TABLECOLUMN_CODE")) != null) {
            ViewOuput buildViewOuPut = columnsInfo.get(column.getStr("TABLECOLUMN_CODE"));
            column.set("TABLECOLUMN_NAME", buildViewOuPut.getName());
            column.set("TABLECOLUMN_VIEWCONFIG", ViewOuput.toString(buildViewOuPut, masterTableId));
            //存储视图列的配置信息
            String type = buildViewOuPut.getDataType();
            if (StringUtil.isNotEmpty(type)) {
                column.set("TABLECOLUMN_TYPE", type);
                if (Strings.isNullOrEmpty(buildViewOuPut.getLength())) {
                    column.set("TABLECOLUMN_LENGTH", buildViewOuPut.getLength());
                }
                if ("ID".equals(type)) {
                    pkCode = column.getStr("TABLECOLUMN_CODE");
                }
            }

        }
        return pkCode;
    }

    @Override
    @Transactional
    public String getViewCreateSql(String tableCode, List<Map<String, Object>> viewColumnList) {
        String createSql = "";
        if (ConstantVars.STR_ORACLE.equals(JEDatabase.getCurrentDatabase())
                || ConstantVars.STR_SHENTONG.equals(JEDatabase.getCurrentDatabase())
                || ConstantVars.STR_KINGBASEES.equals(JEDatabase.getCurrentDatabase())
                || ConstantVars.STR_DM.equals(JEDatabase.getCurrentDatabase())) {
            JdbcUtil jdbcUtil = JdbcUtil.getInstance();
            List<HashMap> lists = jdbcUtil.query("SELECT VIEW_NAME,TEXT FROM USER_VIEWS WHERE VIEW_NAME='" + tableCode + "'");
            if (lists != null && lists.size() > 0) {
                createSql = lists.get(0).get("TEXT") + "";
                if (StringUtil.isNotEmpty(createSql)) {
                    createSql = createSql.replaceAll("\r\n", " \r\n");
                    createSql = createSql.replaceAll("\n", " \n");
                }
            }
            jdbcUtil.close();
        } else if (ConstantVars.STR_MYSQL.equals(JEDatabase.getCurrentDatabase()) || ConstantVars.STR_TIDB.equals(JEDatabase.getCurrentDatabase())) {
            List<Map<String, Object>> lists;
            if (viewColumnList == null) {
                lists = metaService.selectSql("SHOW CREATE VIEW " + tableCode + "");
            } else {
                lists = viewColumnList;
            }
            if (lists != null && lists.size() > 0) {
                createSql = lists.get(0).get("Create View") + "";
                if (StringUtil.isNotEmpty(createSql)) {
                    int createIndex = createSql.indexOf("AS");
                    if (createIndex != -1) {
                        createSql = createSql.substring(createIndex + 3);
                    }
                }
                if (StringUtil.isNotEmpty(createSql)) {
                    createSql = createSql.replaceAll("\r\n", " \r\n");
                    createSql = createSql.replaceAll("\n", " \n");
                    List<Map<String, Object>> dbNameList = metaService.selectSql("select database()  db");
                    createSql = createSql.replaceAll("`" + dbNameList.get(0).get("db") + "`.", "");
                }
            }
        } else {
            List<Map<String, Object>> lists = metaService.selectSql("sp_helptext '" + tableCode + "'");
            StringBuffer createVal = new StringBuffer();
            if (lists != null && lists.size() > 0) {
                for (Map v : lists) {
                    createVal.append(v.get("Text"));
                }
            }
            createSql = createVal.toString();
            if (StringUtil.isNotEmpty(createSql)) {
                int createIndex = createSql.indexOf("AS");
                if (createIndex != -1) {
                    createSql = createSql.substring(createIndex + 3);
                    createSql = createSql.replaceAll("\r\n", " \r\n");
                    createSql = createSql.replaceAll("\n", " \n");
                }
            }
        }
        return createSql;
    }


}
